<script setup>
import { reactive, ref } from "vue";
import { addRole, editRolelnfo, getMenu, editRole } from "@/api/role";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getUrlParam } from "@zzcpt/zztool"
const router = useRouter();

const queryParam = getUrlParam();

const treeRef = ref();
const treeData = ref();
const formRef = ref();
const formData = reactive({
  id: 0,
  name: "",

  menu: [],
});
const formDataRule = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});
const expand = ref(true);
const defaultCheckedKeys = ref([]);

getTree();
async function getTree() {
  const res = await getMenu();
  treeData.value = res.data;
}
getUserInfo();
async function getUserInfo() {
  if (!queryParam.id) return;
  const res = await editRolelnfo(queryParam);
  const data = res.data;
  formData.name = data.name;
  formData.id = data.id;
  defaultCheckedKeys.value = data.roles.split(",");
}
const defaultProps = {
  children: "child",
  label: "title",
  disabled: "disabled",
};
const isAllChecked = ref(false);
const toggleCheckAll = () => {
  if (isAllChecked.value) {
    // 取消全选
    treeRef.value.setCheckedKeys([]);
  } else {
    // 全选，获取所有节点的key
    const allKeys = getAllKeys(treeData.value);
    treeRef.value.setCheckedKeys(allKeys);
  }
  // 切换全选状态
  isAllChecked.value = !isAllChecked.value;
};

const getAllKeys = (nodes) => {
  let keys = [];
  nodes.forEach((node) => {
    keys.push(node.id);
    if (node.children) {
      keys = keys.concat(getAllKeys(node.children));
    }
  });
  return keys;
};
const getCheckKeys = () => {
  return treeRef.value.getCheckedKeys();
};
const toggleExpandAll = () => {
  if (expand.value) {
    expand.value = false;
    Object.values(treeRef.value.store.nodesMap).forEach((v) => v.expand());
    return;
  }
  expand.value = true;
  Object.values(treeRef.value.store.nodesMap).forEach((v) => v.collapse());
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      formData.menu = getCheckKeys().toString();
      if (queryParam.id) {
        editRole(formData).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: "修改成功",
              type: "success",
            });
            router.push("/role/group");
          }
        });
        return;
      }
      addRole(formData).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          router.push("/role/group");
        }
      });
    } else {
      return false;
    }
  });
};
</script>

<template>
  <div class="container">
    <p class="title">{{ queryParam.id ? "修改角色" : "添加角色" }}</p>
    <div class="box">
      <el-form
        ref="formRef"
        label-width="auto"
        status-icon
        :rules="formDataRule"
        :model="formData"
      >
        <el-form-item prop="name" label="角色名称">
          <el-input
            style="width: 200px"
            v-model="formData.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色授权">
          <div>
            <div>
              <el-button @click="toggleExpandAll()">{{
                expand ? "展开" : "折叠"
              }}</el-button>
              <el-button @click="toggleCheckAll()">全选</el-button>
            </div>

            <el-tree
              ref="treeRef"
              empty-text="加载中..."
              v-model="formData.menu"
              style="max-width: 600px"
              :data="treeData"
              node-key="id"
              :props="defaultProps"
              :default-checked-keys="defaultCheckedKeys"
              show-checkbox
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
